package com.tsd.core.utils;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import java.io.*;
import java.net.URL;
import java.net.URLConnection;
import java.nio.ByteBuffer;
import java.nio.channels.FileChannel;
import java.text.SimpleDateFormat;
import java.util.Base64;
import java.util.Date;
import java.util.Random;
import java.util.regex.Pattern;
import java.util.zip.GZIPInputStream;

/**
 * 文件操作工具类
 *
 * @Author Hillpool
 * @Date 2019/3/11 16:10
 */
public class FileUtil {

    private static final Log LOG = LogFactory.getLog(FileUtil.class);
    private final static String IMAGE_EXT = "jpg|png|gif|bmp|jpeg";
    private final static String VIDEO_EXT = "avi|mp4|wma|rmvb|rm|flash|3gp|flv";
    private final static String AUDIO_EXT = "mp3|wav|mid|ogg|amr";
    private final static String FILE_EXT = "pdf|doc|docx|xls|xlsx|txt|ppt|pptx";
    private static final String sdfDateFormat = "yyyy_MM_dd.HH.mm.ss";
    static String ExceptionLogPath = null;
    static String base64Tag = ";base64,";
    //与base64Tag的长度对应
    static int base64TagLength = base64Tag.length();

    /**
     * 下载网络文件到本地
     *
     * @param urlString 被下载的文件地址
     * @param filename  本地文件名
     * @throws Exception 各种异常
     */

    public static boolean download(String urlString, String filename) {
        boolean ret = false;
        // 构造URL
        URL url;
        InputStream is = null;
        GZIPInputStream gis = null;
        OutputStream os = null;
        try {
            url = new URL(urlString);
            URLConnection con = url.openConnection();// 打开连接
//		con.setConnectTimeout(5 * 1000);//超时
            // 输入流
            is = con.getInputStream();
            String code = con.getHeaderField("Content-Encoding");
            // 1K的数据缓冲
            byte[] bs = new byte[1024];
            // 读取到的数据长度
            int len;

            //文件路径没有就创建
            File filedir = new File(getPath(filename));
            if (!filedir.exists()) {
                filedir.mkdirs();
            }

            // 输出的文件流
            os = new FileOutputStream(filename);

            if ((null != code) && code.equals("gzip")) {//压缩文件单独处理
                gis = new GZIPInputStream(is);
                while ((len = gis.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }

            } else {
                while ((len = is.read(bs)) != -1) {
                    os.write(bs, 0, len);
                }
            }
            ret = true;
        } catch (Exception e) {
            LOG.error("download(String)  file:" + filename, e);
        } finally {
            safeCloseInputStrem(gis);
            safeCloseInputStrem(is);
            safeCloseOutputStrem(os);
        }
        return ret;
    }

    public static void download(String urlString, String filename, String savePath) throws Exception {
        download(urlString, savePath + "\\" + filename);
    }

    /**
     * 判断文件或者目录是否存在
     *
     * @param pathname
     * @return
     */
    public static boolean ifExists(String pathname) {
        return new File(pathname).exists();
    }

    /**
     * 删除文件
     *
     * @param pathname
     * @return
     */
    public static boolean delete(String pathname) {
        try {
            File file = new File(pathname);
            if (file.exists()) {
                file.delete();
            }
            return true;
        } catch (Exception e) {
            LOG.error("delete(String) String f:" + "f", e);
            return false;
        }
    }

    /**
     * 递归删除目录下的所有文件及子目录下所有文件
     *
     * @param dir 将要删除的文件目录
     * @return
     */
    public static boolean deleteDir(File dir) {
        if (dir.isDirectory()) {
            String[] children = dir.list();
            if (children != null) {
                // 递归删除目录中的子目录下
                for (String child : children) {
                    boolean success = deleteDir(new File(dir, child));
                    if (!success) {
                        return false;
                    }
                }
            }
        }
        // 目录此时为空，可以删除
        return dir.delete();
    }

    /**
     * 读文件内容以指定的字符集返回字符串
     *
     * @param file 路径
     * @return
     * @throws UnsupportedEncodingException
     */
    public static String read(String file, String charset) throws UnsupportedEncodingException {
        byte[] bytes = readBytes(file);
        return bytes == null ? null : new String(bytes, charset);
    }

    /**
     * 读文件到子节数组中返回
     *
     * @param file 路径
     * @return
     */
    public static byte[] readBytes(String file) {
        byte[] ret = null;
        BufferedInputStream inputStream = null;
        ByteArrayOutputStream outputStream = null;

        try {
            File f = new File(file);
            if (!f.exists()) {
                if (LOG.isDebugEnabled()) {
                    LOG.debug(file + " does not exist.");
                }
                return null;
            } else if (!f.isFile()) {
                // fix bug:判断是否是文件,如果是一个目录是很危险的
                LOG.warn(file + " is not a file.");
                return null;
            }
            inputStream = new BufferedInputStream(new FileInputStream(f));
            outputStream = new ByteArrayOutputStream();
            byte[] cont = new byte[1024];
            int conlen;
            while ((conlen = inputStream.read(cont)) >= 0) {
                outputStream.write(cont, 0, conlen);
            }
            outputStream.flush();
            ret = outputStream.toByteArray();
        } catch (Exception e) {
            LOG.error("read(String)  file:" + file, e);
        } finally {
            safeCloseInputStrem(inputStream);
            safeCloseOutputStrem(outputStream);
        }
        return ret;
    }

    /**
     * 写文件(覆盖方式）
     *
     * @param content 内容
     * @param file    文件名
     * @return
     */
    public static boolean write(String content, String file) {
        return write(content, file, false);
    }

    /**
     * @param content 内容
     * @param file    文件名
     * @param append  是否追加模式
     * @return 是否成功
     */
    public static boolean write(String content, String file, boolean append) {
        return write(content, file, append, "UTF-8");
    }

    /**
     * 写文件
     *
     * @param content  字节内容
     * @param file     文件名
     * @param append   追加
     * @param encoding 字符编码
     * @return 是否成功
     */
    public static boolean write(String content, String file, boolean append, String encoding) {
        boolean ret = false;
        OutputStreamWriter osw = null;
        FileOutputStream fos = null;
        try {
            File filedir = new File(getPath(file));
            if (!filedir.exists()) {
                filedir.mkdirs();
            }
            if (append) {
                fos = new FileOutputStream(file, append);
            } else {
                fos = new FileOutputStream(file);
            }
            //String encoding="UTF-8";
            osw = new OutputStreamWriter(fos, encoding);
            osw.write(content);
            osw.flush();
            //BufferedWriter bw = new BufferedWriter (new OutputStreamWriter (new FileOutputStream ("c:/content1.txt"), "UTF-8"));
			/*
			 * Writer out = new OutputStreamWriter(fos, "UTF-8");
			out.write(content);*/
            //fos.write(content);
            ret = true;
        } catch (Exception e) {
            LOG.error("write(String,String,boolean) file=" + file, e);
            return false;
        } finally {
            try {
                if (osw != null) {
                    osw.close();
                }
            } catch (Exception e) {
                LOG.error(e);
            }
            safeCloseOutputStrem(fos);
        }
        return ret;
    }

    /**
     * 将字节数组保存到文件
     *
     * @param content
     * @param file
     * @return
     * @throws IOException
     */
    public static void write(byte[] content, String file) throws IOException {
        FileOutputStream fos = null;
        try {
            File filedir = new File(getPath(file));
            if (!filedir.exists()) {
                filedir.mkdirs();
            }
            fos = new FileOutputStream(file);
            fos.write(content);
        } finally {
            safeCloseOutputStrem(fos);
        }
    }

    /**
     * 获取字符串中路径部分
     * 取上级目录，如果不为空，则获取上级目录的绝对路径，否则返回当前路径
     *
     * @param f
     * @return
     */
    public static String getPath(String f) {
        File file = new File(f);
        if (file.getParentFile() != null) {
            return file.getParentFile().getAbsolutePath();
        } else {
            return file.getAbsolutePath();
        }
    }

    /**
     * 获取目录里面的文件
     *
     * @param dir
     * @return
     */
    public static String[] getFileList(String dir) {
        try {
            File parent = new File(dir);
            if (!parent.isAbsolute() || !parent.isDirectory()) {
                return null;
            }
            return parent.list();
        } catch (Exception e) {
            return null;
        }
    }

    /**
     * 获取目录内指定过滤模式的文件名称列表
     *
     * @param dir
     * @param pattern
     * @return
     */
    public static String[] getFileList(final String dir, final String pattern) {
        try {

            File parent = new File(dir);
            if (!parent.isAbsolute() || !parent.isDirectory()) {
                return null;
            }
            final Pattern namePattern = Pattern.compile(pattern);
            return parent.list(new FilenameFilter() {
                public boolean accept(File dir, String name) {
                    return namePattern.matcher(name).matches();
                }
            });

        } catch (Throwable te) {
            LOG.error("getFileList[dir=" + dir + ",pattern=" + pattern + "]error.", te);
            return null;
        }

    }

    /**
     * 判断文件是否存在一个目录中
     *
     * @param fileName 文件名
     * @param dir      目录名
     * @return 文件是否存在
     */
    public static boolean isFileExist(String fileName, String dir) {
        File files = new File(dir, fileName);
        return files.exists();
    }

    /**
     * 判断文件是否存在
     *
     * @param fileName 包含路径的文件名
     * @return 文件是否存在
     */
    public static boolean isFileExist(String fileName) {
        File files = new File(fileName);
        return files.exists();
    }

    /**
     * 判断文件是否图片
     *
     * @param fileName
     * @return
     */
    public static boolean isPictureFile(String fileName) {
        String n = fileName.toLowerCase();
        return n.endsWith(".jpg") || n.endsWith(".jpeg") || n.endsWith(".gif") || n.endsWith(".png") || n.endsWith(".bmp");
    }

    /**
     * 得到文件的后缀(文件类别),包括点号
     *
     * @param fileName 文件名
     * @return 含点号的扩展名
     */
    public static String getFileType(String fileName) {
        String type = "";
        if (null == fileName || "".equals(fileName.trim())) {
            return type;
        }

        if (fileName.lastIndexOf(".") != -1) {
            type = fileName.substring(fileName.lastIndexOf("."));
        }

        return type;
    }

    /**
     * 得到文件不含点号和扩展名的文件名
     *
     * @param fileName 文件名
     * @return
     */
    public static String getFileNameWithoutExt(String fileName) {
        if (fileName != null) {
            int pos = fileName.lastIndexOf(".");
            if (pos == -1) {
                return fileName;
            } else {
                return fileName.substring(0, pos);
            }
        } else {
            return fileName;
        }
    }

    /**
     * 获得随机文件名,保证在同一个文件夹下不同名
     *
     * @param fileName 原文件名
     * @param dir      目录
     * @return 随机文件名
     */
    public static String getRandomFileName(String fileName, String dir) {
        String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
        String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀

        Random random = new Random();
        int add = random.nextInt(1000000); // 产生随机数10000以内
        String ret = add + extendFile;
        while (isFileExist(ret, dir)) {
            add = random.nextInt(1000000);
            ret = fileName + add + extendFile;
        }
        return ret;
    }

    /**
     * 获得按日期格式生成的文件名,保证在同一个文件夹下不同名
     *
     * @param fileName 原文件名
     * @param dir      目录
     * @param pattern  日期格式
     * @return 如果已经存在这样的文件名，则返回自动进行命名的文件名
     * xxx.txt,如果已经存在，则得到xxx_1.txt,如果xxx_1.txt存在，则得到xxx_2.txt依次类推
     */
    public static String getRandomFileName(String fileName, String dir, String pattern) {
        String[] split = fileName.split("\\.");// 将文件名已.的形式拆分
        String extendFile = "." + split[split.length - 1].toLowerCase(); // 获文件的有效后缀
        String newFileName = split[0] + new SimpleDateFormat(pattern).format(new Date()) + extendFile;
        return getAutoFileRename(newFileName);
    }

    /**
     * 当文件已经存在时自动进行命名的文件名
     * xxx.txt,如果已经存在，则得到xxx_1.txt,如果xxx_1.txt存在，则得到xxx_2.txt依次类推
     *
     * @param fileName 计划保存的文件名
     * @return 自动命名的文件名
     */
    public static String getAutoFileRename(String fileName) {
        if (null == fileName || "".equals(fileName.trim())) {
            return fileName;
        }
        File file = new File(fileName);
        if (!file.exists()) {
            return fileName;
        }
        String fName = fileName;
        String ext = null;

        if (fileName.lastIndexOf(".") != -1) {
            int index = fileName.lastIndexOf(".");
            ext = fileName.substring(index);
            fName = fileName.substring(0, index);
        }
        int i = 1;
        while (file.exists()) {
            file = new File(fName + "_" + i + ext);
            i++;
        }
        return fName + "_" + (i - 1) + ext;
    }

    /**
     * 文件改名
     *
     * @param source 原文件名
     * @param dest   改为文件名
     * @return 改名是否成功
     */
    public static boolean renameFile(String source, String dest) {
        File s = new File(source);
        File d = new File(dest);
        boolean res = s.renameTo(d);
        s = null;
        d = null;
        return res;
    }

    /**
     * copy 文件
     *
     * @param source    源文件全路径
     * @param dest      目标文件路径
     * @param overWrite 是否覆盖
     * @throws IOException
     */
    public static void copyFile(String source, String dest, boolean overWrite) throws IOException {
        if (new File(dest).exists() && !overWrite) {
            throw new IOException("文件已存在");
        }
        byte[] iobuff = new byte[10240];
        int bytes;
        FileInputStream fis = new FileInputStream(source);
        FileOutputStream fos = new FileOutputStream(dest);
        try {
            while ((bytes = fis.read(iobuff)) != -1) {
                fos.write(iobuff, 0, bytes);
            }
        } finally {
            safeCloseInputStrem(fis);
            safeCloseOutputStrem(fos);
        }
    }

    /**
     * copy file using NIO Channel 通过文件流 拷贝source文件到dest
     *
     * @param source 源文件路径
     * @param dest   目标文件路径
     * @throws IOException
     */
    public static void NIOCopyFile(String source, String dest) throws IOException {
        FileInputStream inData = new FileInputStream(source);
        FileChannel inChannel = inData.getChannel();
        FileOutputStream opData = new FileOutputStream(dest);
        FileChannel opChannel = opData.getChannel();

        try {
            inChannel.transferTo(0, inChannel.size(), opChannel);
        } finally {
            if (inChannel.isOpen()) {
                inChannel.close();
            }
            if (opChannel.isOpen()) {
                opChannel.close();
            }
            safeCloseInputStrem(inData);
            safeCloseOutputStrem(opData);
        }
    }

    /**
     * 获取不含路径的文件名，根据全路径文件名获取简单的文件名（不包含路径）
     *
     * @param fullFileName 全路径文件名
     * @return 不含路径文件名
     */
    public static String getFileNameWithoutPath(String fullFileName) {
        //如果文件不存在，使用new File(fullFileName).getName()来取得文件名的话，将返回空，不能取得简单的文件名
        String name = fullFileName.replace("\\\\", File.separator);
        name = name.replace("/", File.separator);
        int pos = name.lastIndexOf(File.separator);
        if (pos > 0) {
            name = name.substring(pos + 1);
        }
        return name;
    }

    /**
     * 合并文件路径
     *
     * @param rootPath
     * @param subPath
     * @return
     */
    public static String mergeFilePath(String rootPath, String subPath) {
        String path = rootPath + "/" + subPath;
        path = path.replace("\\\\", File.separator);
        path = path.replace("/", File.separator);
        return path;
    }

    /**
     * 将一个buf保存到指定的文件中
     *
     * @param fileName    文件名
     * @param buf         byte数组
     * @param ifOverwrite 是否覆盖
     * @return 保存操作是否成功
     * @throws IOException
     */
    public static boolean saveFile(String fileName, byte[] buf,
                                   boolean ifOverwrite) throws IOException {
        boolean result = false;
        File f = new File(fileName);
        if (!f.getParentFile().exists()) {
            f.getParentFile().mkdirs();
        }
        if (f.exists() && !ifOverwrite) {
            return result;
        }
        FileOutputStream output = null;
        output = new FileOutputStream(f);
        try {
            output.write(buf);
        } finally {
            safeCloseOutputStrem(output);
        }

        result = f.exists();
        return result;
    }

    /**
     * 把input里面的数据保存到文件
     *
     * @param input       待保存的InputStream
     * @param dest        文件名
     * @param ifOverwrite 是否覆盖
     * @return 保存操作是否成功
     * @throws IOException
     */
    public static boolean saveFile(InputStream input, String dest, boolean ifOverwrite) throws IOException {
        boolean result = false;
        File f = new File(dest);
        if (f.exists() && !ifOverwrite) {
            return result;
        }
        byte[] iobuff = new byte[1024];
        int bytes;

        FileOutputStream fos = new FileOutputStream(dest);
        try {
            while ((bytes = input.read(iobuff)) != -1) {
                fos.write(iobuff, 0, bytes);
            }
        } finally {
            safeCloseOutputStrem(fos);
        }

        result = f.exists();
        return result;
    }

    /**
     * 获取文件媒介类型
     *
     * @param ext
     * @return
     */
    public static String getMediaType(String ext) {
        ext = ext.replace(".", "");
        if (IMAGE_EXT.contains(ext)) {
            return "image";
        } else if (VIDEO_EXT.contains(ext)) {
            return "video";
        } else if (AUDIO_EXT.contains(ext)) {
            return "audio";
        } else if (FILE_EXT.contains(ext)) {
            return "file";
        }
        return null;
    }

    /**
     * @param decoder
     * @param var1
     * @param srcBegin
     * @return
     * @throws IOException
     */
    public static byte[] decodeBufferBase64(Base64.Decoder decoder, String var1, int srcBegin) throws IOException {
        byte[] var2 = new byte[var1.length() - srcBegin];
        var1.getBytes(srcBegin, var1.length(), var2, 0);
        ByteBuffer in = ByteBuffer.wrap(var2);
        ByteBuffer out = decoder.decode(in);
        return out.array();
    }

    /**
     * base64字符串解码后保存到文件
     *
     * @param base64
     * @param filepath
     * @return
     */
    public static boolean base64ToFile(String base64, String filepath) {
        if (HlpUtils.isEmpty(base64)) {
            return false;
        }
        Base64.Decoder decoder = Base64.getDecoder();
        OutputStream outputStream = null;
        try {
            int srcBegin = getBase64ContentBegin(base64);
            byte[] bytes = decodeBufferBase64(decoder, base64, srcBegin);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            outputStream = new FileOutputStream(filepath);
            outputStream.write(bytes);
            outputStream.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            safeCloseOutputStrem(outputStream);
        }
    }

    /**
     * 将Base64编码文件内容解码后替换原文件
     *
     * @param filepath
     */
    public static boolean restoreBase64File(String filepath) {
        File file = new File(filepath);
        String base64File = filepath + ".base64";
//		String tempFile = filepath+".temp";
        if (file.exists()) {
            file.renameTo(new File(base64File));
        }
        Base64.Decoder decoder = Base64.getDecoder();
        FileInputStream inputStream = null;
        FileOutputStream outputStream = null;
        try {
            inputStream = new FileInputStream(base64File);
            InputStream decodeInput = decoder.wrap(inputStream);
            outputStream = new FileOutputStream(filepath);
            byte[] buf = new byte[10240];
            int count = decodeInput.read(buf);
            while (count > -1) {
                if (count > 0) {
                    outputStream.write(buf, 0, count);
                }
                count = decodeInput.read(buf);
            }
            outputStream.flush();
            return true;
        } catch (Exception e) {
            e.printStackTrace();
            return false;
        } finally {
            safeCloseInputStrem(inputStream);
            safeCloseOutputStrem(outputStream);
            delete(base64File);
        }
    }

    /**
     * 一次性读取还原Base64编码文件
     *
     * @param filepath
     */
    public static void restoreBase64FileByOne(String filepath) {
        String base64 = readToString(filepath);
        Base64.Decoder decoder = Base64.getDecoder();
        OutputStream outputStream = null;
        try {
            int srcBegin = 0;
            byte[] bytes = decodeBufferBase64(decoder, base64, srcBegin);
            for (int i = 0; i < bytes.length; i++) {
                if (bytes[i] < 0) {
                    bytes[i] += 256;
                }
            }
            outputStream = new FileOutputStream(filepath);
            outputStream.write(bytes);
            outputStream.flush();
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            safeCloseOutputStrem(outputStream);
        }
    }

    /**
     * 安全关闭输入流
     *
     * @param inputStream
     */
    public static void safeCloseInputStrem(InputStream inputStream) {
        try {
            if (inputStream != null) {
                inputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 安全关闭输出流
     *
     * @param outputStream
     */
    public static void safeCloseOutputStrem(OutputStream outputStream) {
        try {
            if (outputStream != null) {
                outputStream.close();
            }
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 以utf-8字符集读取文件内容返回
     *
     * @param fileName
     * @return
     */
    public static String readToString(String fileName) {
        String encoding = "UTF-8";
        File file = new File(fileName);
        Long filelength = file.length();
        byte[] filecontent = new byte[filelength.intValue()];
        FileInputStream in = null;
        try {
            in = new FileInputStream(file);
            in.read(filecontent);
        } catch (FileNotFoundException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        } finally {
            safeCloseInputStrem(in);
        }
        try {
            return new String(filecontent, encoding);
        } catch (UnsupportedEncodingException e) {
            System.err.println("The OS does not support " + encoding);
            e.printStackTrace();
            return null;
        }
    }


    /**
     * <p>将文件转成base64 字符串</p>
     *
     * @param file 文件路径
     * @return
     */
    public static String encodeFile2Base64(File file) {
        FileInputStream inputFile = null;
        try {
            inputFile = new FileInputStream(file);
            byte[] buffer = new byte[(int) file.length()];
            inputFile.read(buffer);
            return Base64.getEncoder().encodeToString(buffer);
        } catch (Exception e) {
            e.printStackTrace();
        } finally {
            safeCloseInputStrem(inputFile);
        }
        return null;
    }

    /**
     * 获取base64编码字符串的内容开始位置
     *
     * @param base64
     * @return
     */
    public static int getBase64ContentBegin(String base64) {
        return base64.indexOf(base64Tag) + base64TagLength;
    }

    /**
     * 获取Base64文件类型
     * //data:video/mp4;base64,
     * //data:image/jpg;base64,
     *
     * @param base64
     * @return
     */
    public static String getBase64FileType(String base64) {
        String fileType = null;
        String prefStr = null;
        if (base64.length() > 100) {
            prefStr = base64.substring(0, 100);
        } else {
            prefStr = base64;
        }
        int pos1 = prefStr.indexOf("/");
        int pos2 = prefStr.indexOf(";");
        if (pos1 > -1 && pos2 > -1 && pos2 > pos1) {
            fileType = prefStr.substring(pos1 + 1, pos2);
        }
        return fileType;
    }

    /**
     * 追加文本文件
     *
     * @param filePath
     * @param content
     * @throws IOException
     */
    public static void appendFile(String filePath, String content) throws IOException {
        FileWriter fileWriter = null;
        try {
            fileWriter = new FileWriter(filePath, true);
            fileWriter.write(content);
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    /**
     * 追加文本到指定位置
     *
     * @param filePath
     * @param content
     * @throws IOException
     */
    public static void appendFile(String filePath, long index, String content) throws IOException {
        RandomAccessFile fileWriter = null;
        try {
            fileWriter = new RandomAccessFile(filePath, "rw");
            fileWriter.seek(index);
            fileWriter.writeBytes(content);
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    /**
     * 追加子节数组到指定位置
     *
     * @param filePath
     * @param bytes
     * @throws IOException
     */
    public static void appendFile(String filePath, long index, byte[] bytes) throws IOException {
        RandomAccessFile fileWriter = null;
        try {
            fileWriter = new RandomAccessFile(filePath, "rw");
            fileWriter.seek(index);
            fileWriter.write(bytes);
        } finally {
            if (fileWriter != null) {
                fileWriter.close();
            }
        }
    }

    public static void main(String[] args) {
        try {
//			String s = encodeFile2Base64(new File("D:/temp/430-120-3.png"));
//			saveFile("D:/temp/430-120-3.png.txt", s.getBytes("UTF-8"), true);
            restoreBase64FileByOne("D:/temp/430-120-3-text.png");
//            restoreBase64File("d:/temp/430-120-3-1.png");
        } catch (Exception e) {

        }
    }

    /**
     * 删除目录下的所有文件，保留该空目录
     *
     * @param destPath
     */
    public static void deleteFileInDir(String destPath) {
        File target = new File(destPath);
        if (target.exists() && target.isDirectory()) {
            File[] files = target.listFiles();
            for (File file : files) {
                if (file.isDirectory()) {
                    deleteDir(file);
                } else {
                    file.delete();
                }
            }
        }
    }

    /**
     * 直接将扩展名去掉（包括.）
     *
     * @param filePath
     * @return
     */
    public static String getFileNameWithoutExtension(String filePath) {
        int pos = filePath.lastIndexOf(".");
        if (pos > -1) {
            return filePath.substring(0, pos);
        }
        return filePath;
    }

    /**
     * 建立多层目录
     *
     * @param parent
     */
    public static void mkDir(String parent) {
        File file = new File(parent);
        if (!file.exists()) {
            file.mkdirs();
        }
    }
}
